import Vuex from 'vuex'
import Vue from 'vue'
Vue.use(Vuex)

export default  new Vuex.Store({
    // ...组件间共享的数据都要定义在此处
    state:{
      count:1,
      list:JSON.parse(sessionStorage.getItem("list")) || [],
      info:JSON.parse(sessionStorage.getItem("info")) || {},
      musicInfo:{}
    },
    //修改state中的数据的方法，只能定义在mutations
    mutations:{
      // 保存歌曲信息
      savemusic(state,v){
        state.musicInfo = v;
      },
      //保存用户信息
      save(state,v){
        state.info = v ;
        sessionStorage.setItem("info",JSON.stringify(state.info))
      },
      addp(state,a){
        var flag = false;
        state.list.some((shop,index,arr)=>{
          if(shop.id == a.id){
            shop.count++;
            flag = true;
            return;    
          } 
        });
        if(!flag){
          state.list.push(a); 
        }
        sessionStorage.setItem("list",JSON.stringify(state.list));
      },
      jia(state,a){
        state.list.some((shop,index)=>{
          if(shop.id == a.id){
            shop.count++;
            sessionStorage.setItem("list",JSON.stringify(state.list))
            return;
          }
        })
      },
      jian(state,a){
        state.list.some((shop,index)=>{
          if(shop.id == a.id){
            if(shop.count <=1){
              state.list.splice(index,1)
            }else{
              shop.count--;
            }
            sessionStorage.setItem("list",JSON.stringify(state.list))
            return;
          }
        })
      },
      change(state,a){
        state.list.some((shop,index)=>{
          if(shop.id == a.id){
            if(a.count>200){
               shop.count=200;
            }else{
             shop.count = a.count;
            }
            sessionStorage.setItem("list",JSON.stringify(state.list))
           return;
         }
        })
      }
    },
    getters:{
      //专门用来过滤共享数据，相当于state中的数据的计算属性
      allCount(state){
        var count = 0 ;
        state.list.forEach((shop,index,arr)=>{
          count+= shop.count
        })
        return count;
      }
    }
  })